<template>
  <div class="app-container">
    <!-- 查询框 -->
    <div class="filter-container">
      <el-select v-model="pageParam.model.applyStatus" placeholder="选择申请状态" @change="getListByPage">
        <el-option label="显示所有" value="" />
        <el-option label="申请中" value="0" />
        <el-option label="申请成功" value="1" />
        <el-option label="已驳回" value="2" />
        <el-option label="已住院" value="3" />
      </el-select>
      <el-select v-model="pageParam.model.wardType" placeholder="选择病房类型" @change="getListByPage">
        <el-option label="显示所有" value="" />
        <el-option label="普通" value="0" />
        <el-option label="高级" value="1" />
        <el-option label="特护" value="2" />
      </el-select>
    </div>

    <!-- 表格 -->
    <el-table :data="list" fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <!--              @expand-change="getPatientInfoAndRecord">-->

      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">
            <!-- 行数据详情字段 -->
            <el-form-item label="患者姓名">
              <span>{{ row.patient.realName }}</span>
            </el-form-item>
            <el-form-item label="年龄">
              <span>{{ row.patient.age }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span v-if="row.patient.gender=='0'">男性</span>
              <span v-else>女性</span>
            </el-form-item>
            <el-form-item label="身份证">
              <span>{{ row.patient.identityNo }}</span>
            </el-form-item>
            <el-form-item label="医保证">
              <span>{{ row.patient.medicalId }}</span>
            </el-form-item>
            <el-form-item label="联系人姓名">
              <span>{{ row.patient.realName }}</span>
            </el-form-item>
            <el-form-item label="联系人电话">
              <span>{{ row.patient.tellphone }}</span>
            </el-form-item>
            <el-form-item label="诊断时间">
              <span>{{ row.record.checkTime }}</span>
            </el-form-item>
            <el-form-item label="病症">
              <span>{{ row.record.symptom }}</span>
            </el-form-item>
            <el-form-item label="诊断">
              <span>{{ row.record.diagnosis }}</span>
            </el-form-item>
            <el-form-item label="过敏史">
              <span>{{ row.record.allergy }}</span>
            </el-form-item>
            <el-form-item label="传染性疾病">
              <span v-if="row.record.isInfectious=='0'">否</span>
              <span v-else>是</span>
            </el-form-item>

          </el-form>
        </template>
      </el-table-column>

      <!-- 表格字段 -->

      <!-- <el-table-column prop="id" label="">
      </el-table-column> -->

      <el-table-column prop="no" label="住院编号" />

      <el-table-column prop="patient.realName" label="患者姓名" />

      <el-table-column prop="wardType" label="申请入住病房类型">
        <template slot-scope="scope">
          <span v-if="scope.row.wardType==0">普通房</span>
          <span v-if="scope.row.wardType==1">高级房</span>
          <span v-if="scope.row.wardType==2">特护房</span>
        </template>
      </el-table-column>

      <el-table-column sortable="custom" prop="applyTime" label="申请入住时间" />

      <el-table-column prop="applyStatus" label="申请状态">
        <template slot-scope="scope">
          <span v-if="scope.row.applyStatus==0">申请中</span>
          <span v-if="scope.row.applyStatus==1">申请成功</span>
          <span v-if="scope.row.applyStatus==2">已驳回</span>
          <span v-if="scope.row.applyStatus==3">已住院</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <!--          <el-button type="primary" size="small" @click="handleUpdate(row)">编辑</el-button>-->
          <span v-if="row.applyStatus==0">
            <el-button type="danger" size="small" @click="changeApplyStatus(2,row.id)">驳回</el-button>
            <el-button type="primary" size="small" @click="changeApplyStatus(1,row.id)">通过</el-button>
          </span>
          <span v-if="row.applyStatus==1 || row.applyStatus==3">
            <el-button
              :type="row.doctorId==null?'primary':'danger'"
              size="small"
              @click="addArrange(row,row.doctorId==null)"
            >编辑医护人员</el-button>
          </span>
          <el-button v-if="row.applyStatus==2" type="info" size="small" disabled>已驳回</el-button>
          <!--          <el-button v-if="row.applyStatus==0" type="danger" size="small" @click="confirmCheck(row,$index)">禁用-->
          <!--          </el-button>-->
          <!--          <el-button v-if="row.applyStatus==1" type="success" size="small" @click="confirmCheck(row,$index)">确认审核-->
          <!--          </el-button>-->
          <!-- <el-button type="danger" size="small" @click="handleDelete(row,$index)">删除</el-button> -->
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getListByPage"
    />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >

        <!-- 弹窗 -->

        <el-form-item label="输入手机号" prop="tellphone">
          <el-input v-model="temp.tellphone" />
        </el-form-item>

        <!-- <el-form-item label="审核状态 0待审核 1待发布 2已删除" prop="checkStatus">
          <el-input v-model="temp.checkStatus" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible2">
      <el-form
        ref="dataForm2"
        :rules="rules"
        :model="temp2"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >

        <!-- 弹窗2-->
        <el-form-item label="入院科室" prop="dep">
          <span>{{ depName }}</span>
        </el-form-item>
        <el-form-item label="患者名称" prop="name">
          <span>{{ patient2.realName }}</span>
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <span>{{ patient2.age }}</span>
        </el-form-item>
        <el-form-item label="患者性别" prop="gender">
          <template>
            <el-radio v-if="patient2.gender==0" :aria-checked="true">女性</el-radio>
            <el-radio v-else :aria-checked="true">男性</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <template>
            <el-radio v-model="temp2.applyStatus" label="0">申请中</el-radio>
            <el-radio v-model="temp2.applyStatus" label="1">申请成功</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="病房类型" prop="wardType">
          <template>
            <el-radio v-model="temp2.wardType" label="0">普通</el-radio>
            <el-radio v-model="temp2.wardType" label="1">高级</el-radio>
            <el-radio v-model="temp2.wardType" label="2">特护</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="预约日期" prop="applyTime">
          <template>
            <div class="block">
              <el-date-picker
                v-model="temp2.applyTime"
                type="date"

                placeholder="选择日期"
              />
            </div>
          </template>
        </el-form-item>
        <el-form-item label="申请信息备注" prop="applyInfo">
          <el-input v-model="temp2.applyInfo" />
        </el-form-item>
        <el-form-item label="查看病历" prop="showRecord">
          <template>
            <el-switch
              v-model="dialogFormVisible3"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="showRecodWin()"
            />
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">
          取消
        </el-button>
        <el-button type="primary" @click="createNewApply()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible3">
      <el-form
        ref="dataForm3"
        :rules="rules"
        :model="record2"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >

        <!-- 弹窗3-->
        <el-form-item label="主治医生" prop="doctorName">
          <el-input v-model="doctorName" />
        </el-form-item>
        <el-form-item label="疾病症状" prop="symptom">
          <el-input v-model="record2.symptom" />
        </el-form-item>
        <el-form-item label="医生诊断" prop="diagnosis">
          <el-input v-model="record2.diagnosis" />
        </el-form-item>
        <el-form-item label="过敏史" prop="allergy">
          <el-input v-model="record2.allergy" />
        </el-form-item>
        <el-form-item label="传染性" prop="isInfectious">
          <template>
            <el-radio v-model="record2.isInfectious" label="0">否</el-radio>
            <el-radio v-model="record2.isInfectious" label="1">是</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="是否复诊" prop="isRecheck">
          <template>
            <el-radio v-model="record2.isRecheck" label="0">否</el-radio>
            <el-radio v-model="record2.isRecheck" label="1">是</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="检查日期" prop="checkTime">
          <template>
            <div class="block">
              <el-date-picker
                v-model="record2.checkTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
              />
            </div>
          </template>
        </el-form-item>

        <!-- <el-form-item label="审核状态 0待审核 1待发布 2已删除" prop="checkStatus">
          <el-input v-model="temp.checkStatus" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateRecord">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="医护人员编辑">
      <el-form
        :model="temp"
        label-position="right"
        label-width="140px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="护士姓名">
          <el-select v-model="arrange.nurseId" placeholder="请选择护理人员">
            <el-option v-for="item in nurseList" :key="item.id" :label="item.realName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="医生姓名">
          <el-select v-model="arrange.doctorId" placeholder="请选择医生">
            <el-option v-for="item in doctorList" :key="item.id" :label="item.realName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="arrangeSubmit">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

// application api
import {
  getApplication,
  showPatientInfo,
  showPatientRecord,
  upadteApplication,
  getPatientInfoByTellphone,
  getCurrentUserDep,
  getApplicationByPatientId,
  getDoctorNameByDoctorId,
  updateRecordById
} from '@/api/application/application'

import {
  getNurseByDepId,
  getDoctorByDepId
} from '@/api/his_user/his_user'

// 导入组件 分页 记得声明组件
import Pagination from '@/components/Pagination'

export default {
  components: { // 在这里声明组件
    Pagination
  },
  data() {
    return {
      dialogVisible: false,
      arrange: {
        id: undefined,
        nurseId: '',
        doctorId: '',
        applyStatus:''
      },
      patient: {
        realName: '',
        age: '',
        gender: '',
        identityNo: '',
        medicalId: '',
        tellphone: '',
        relaPhone: ''
      },
      patient2: {
        id: '',
        realName: '',
        age: '',
        gender: '',
        identityNo: '',
        medicalId: '',
        tellphone: '',
        relaPhone: ''
      },
      record: {
        symptom: '',
        diagnosis: '',
        allergy: '',
        isInfectious: '',
        doctorId: '',
        checkTime: ''
      },
      record2: {
        id: '',
        symptom: '',
        diagnosis: '',
        allergy: '',
        isInfectious: '',
        doctorId: '',
        checkTime: '',
        isRecheck: ''
      },
      depName: '',
      doctorName: '',
      switchStatus: false,
      list: [], // 列表数据
      total: 0,
      listQuery: { // 分页 排序  查询参数
        pageNum: 1,
        pageSize: 5
      },
      fieldQuery: { // 按字段查询
        realName: ''
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      temp: {
        tellphone: ''
      },
      temp2: {
        id: '',
        patientId: '',
        recordId: '',
        applyTime: '',
        depId: '',
        applyType: '0',
        inTime: '',
        applyStatus: '0',
        applyInfo: '',
        wardType: '',
        doctorId: '',
        nurseId: '',
        status: ''
      },
      tempImageList: [],
      rules: {},
      pageParam: {
        pageNum: 1,
        pageSize: 5,
        model: {
          'applyStatus': undefined,
          'wardType': undefined
        },
        orderParams: [
          ''
        ],
        superSearchKeyWord: ''
      },
      roleList: [],
      doctorList: [],
      nurseList: []
    }
  },
  computed: {

    editor() {
      return this.$refs.myQuillEditor.quill
    }

  },
  created() {
    this.getListByPage()
  },
  methods: {
    // 添加医护人员
    addArrange(row,flag) {
      if(flag){
        this.arrange.applyStatus='3'
      }
      this.doctorList = []
      this.nurseList = []
      this.arrange.doctorId = ''
      this.arrange.nurseId = ''
      // 查询医护人员信息
      getDoctorByDepId(row.depId).then(res => {
        this.doctorList = res.content
      })
      getNurseByDepId(row.depId).then(res => {
        this.nurseList = res.content
      })
      this.dialogPvVisible = true
      this.arrange.id = row.id
    },
    arrangeSubmit() {
      upadteApplication(this.arrange).then(res => {
        this.$notify({
          title: 'Success',
          message: 'Created Successfully',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
        this.dialogPvVisible = false
      })
    },
    // 更新病历操作
    updateRecord() {
      updateRecordById(this.record2).then(res => {
        if (res.code == 20000) {
          this.dialogFormVisible3 = false
        }
      })
    },
    // 实际是更新申请表，预申请时已经生成了申请表信息
    createNewApply() {
      upadteApplication(this.temp2).then(res => {
        if (res.code == 20000) {
          this.dialogFormVisible2 = false
        }
      })
    },
    // 显示病历窗口
    showRecodWin() {
      showPatientRecord(this.patient2.id).then(res => {
        this.record2 = res.content
        getDoctorNameByDoctorId(this.record2.doctorId).then(res => {
          if (res.content != null) {
            this.doctorName = res.content.realName
          } else {
            this.doctorName = '尚未指派主治医师'
          }
        })
      })
    },
    // 改变申请状态
    changeApplyStatus(obj1, obj2) {
      upadteApplication({
        id: obj2,
        applyStatus: obj1
      }).then(res => {
        // location.reload()
        this.getListByPage()
      })
    },
    // 列表获取病人的信息和病历信息
    getPatientInfoAndRecord(row, rowlist) {
      // alert(123);
      // rowlist == null
      // console.log(row.id)
      // 显示病人信息
      showPatientInfo(row.id).then(res => {
        // console.log("--------------------------------------------")
        if (res.content != null) {
          this.patient = res.content
          // console.log(this.patient)
        }
      })
      // 显示病历信息
      showPatientRecord(row.patientId).then(res => {
        if (res.content != null) {
          this.record = res.content
        }
        // console.log(res.content.symptom)
      })
    },
    sortChange(val) {
      // console.log("排序参数",val)
      const prop = val.prop
      const order = val.order === 'ascending' ? 'asc' : 'desc'
      const orderParam = 'apply_time' + ' ' + order
      // console.log(orderParam)
      this.pageParam.orderParams.push(orderParam)
      console.log(this.pageParam.orderParams)
      this.getListByPage()
    },
    getTempImageList() {
      // 清空文件列表
      this.tempImageList = []

      const tempPageParam = this.pageParam
      tempPageParam.model = {
        productId: this.temp.id
      }
      tempPageParam.pageSize = 1000
      searchSomeProductimageByPage(tempPageParam).then(res => {
        // console.log(res)
        const resList = res.content.list
        const tempImageData = {
          name: '',
          url: '',
          key: ''
        }
        this.$refs.imagesUpload.clearFiles()
        for (let i = 0; i < resList.length; i++) {
          tempImageData.name = resList[i].imageUrl
          tempImageData.url = resList[i].imageUrl
          tempImageData.key = resList[i].imageUrl
          this.tempImageList.push(tempImageData)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 显示当前页列表带分页
    getListByPage() {
      this.pageParam.pageNum = this.listQuery.pageNum
      this.pageParam.pageSize = this.listQuery.pageSize

      console.log(this.pageParam.orderParams)
      // 加载申请列表
      getApplication(this.pageParam).then(res => {
        // console.log(res)
        this.list = res.content.list
        for (const i of res.content.list) {
          if (i.applyStatus === '0') {
            this.appliyStatusName = '申请中'
            // this.switchStatus[i] = false
          }
          // this.switchStatus[i] = true
        }
        this.total = res.content.total
      }).catch(err => {
        console.log(err)
      })
    },
    handleCreate() {
      this.tempImageList = []
      // this.$refs.imagesUpload.clearFiles()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      console.log('edit:' + row)
      this.temp = Object.assign({}, row) // copy obj
      this.temp.id = row.id
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      const temp = {
        id: row.id
      }

      deleteOneProductTrue(temp).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
      })
    },
    // 通过手机号打开新建申请列表信息窗口
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 通过手机号查询病人信息
          getPatientInfoByTellphone(this.temp.tellphone).then(res => {
            // this.tempImageList = []
            // this.$refs.imagesUpload.clearFiles()
            // this.resetTemp()
            this.dialogFormVisible = false
            this.patient2 = res.content
            this.dialogStatus = 'create'
            this.dialogFormVisible2 = true
            this.$nextTick(() => {
              this.$refs['dataForm2'].clearValidate()
            })
            // 通过当前登陆用户获得科室名称
            getCurrentUserDep().then(res => {
              this.depName = res.content.depName
            })
            // 通过病人id获取预申请的信息
            getApplicationByPatientId(this.patient2.id).then(res => {
              this.temp2 = res.content
            }
            )
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateNewscategory(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    confirmCheck(row) {
      console.log('edit:' + row)
      const temp = Object.assign({}, row) // copy obj
      temp.checkStatus = temp.checkStatus == 1 ? 0 : 1
      updateNewscategory(temp).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: temp.checkStatus == 1 ? '禁用成功' : '审核成功',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
      })
    },
    resetTemp() {
      this.temp = {
        id: '',
        categoryName: '',
        viewNum: undefined,
        createUserId: '',
        updateUserId: '',
        createTime: undefined,
        updateTime: undefined,
        isDeleted: undefined,
        checkStatus: undefined
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)

      const imageUrl = file.response == undefined ? file.url.replace('blob:', '') : file.response.content
      // let imageUrl = ''
      const productImageData = {
        imageUrl: imageUrl
      }
      deleteSomeProductimageTrueByCondition(productImageData).then(() => {

      })
    },
    handlePictureCardPreview(file) {
      console.log(file, fileList)
      // this.dialogImageUrl = file.url;
      console.log(file.url)
      this.temp.productImages = file.url
      this.dialogVisible = true
    },
    handleImageSuccess(res, file) {
      // console.log(res,file)
      // this.temp.headPic = URL.createObjectURL(file.raw);
      // this.temp.productImages = res.content

      const productImageData = {
        imageUrl: res.content,
        productId: this.temp.id
      }
      addOneProductimage(productImageData).then(() => {

      })
    },
    beforeAvatarUpload(file) {
      console.log(file)
      const fileName = file.name
      const isImage = /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 gif|jpg|jpeg|png|gif|jpg|png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    onEditorBlur(quill) {

      // console.log('editor blur!', quill)

    },

    onEditorFocus(quill) {

      // console.log('editor focus!', quill)

    },

    onEditorReady(quill) {

      // console.log('editor ready!', quill)

    },

    onEditorChange({
      quill,
      html,
      text
    }) {
      console.log('editor change!', quill, html, text)

      this.temp.description = html
    }
  }

}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
